import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import CourseRecordListABI from "../contract/ABIs/CourseList.json"; // 课程记录列表合约 ABI
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI

import CourseRecordListAddress from "../contract/ADDRESSes/CourseListAddress.js" // 课程记录列表合约地址
import UserNavBar from './nav/UserNavBar.js';
// import '../static/indexcss/aacsss.css';
import Eye from './Eye.js'

const User_registerStudent = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [isUser, setisUser] = useState(false);
    const [contractUser, setcontractUser] = useState(false);
    const [StudentInfo, setStudentInfo] = useState(null);
    const [registerStudent, setregisterStudent] = useState('');
    const [realName, setrealName] = useState('');
    const [idNumber, setidNumber] = useState('');
    const [studentIDNumber, setstudentIDNumber] = useState('');



    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseRecordListInstance = new web3Instance.eth.Contract(
                        CourseRecordListABI,
                        CourseRecordListAddress
                    );
                    setcontractCourseRecordList(courseRecordListInstance);

                    // 创建管理员合约实例
                    const userInstance = new web3Instance.eth.Contract(
                        UserABI,
                        address
                    );
                    setcontractUser(userInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await userInstance.methods.getUserAddr().call();
                    console.log("currentAddress:", currentAddress, "ownerAddress:", ownerAddress);
                    // 检查当前账户是否是用户本人
                    setisUser(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);




    const RegisterStudent = async (event) => {
        event.preventDefault();
        if (contractCourseRecordList) {
            try {
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress);
                await contractCourseRecordList.methods.registerStudent(realName, idNumber, studentIDNumber).send({ from: fromAddress }).then((result) => {
                    console.log("result:", result);
                    alert("注册成功");

                });

            } catch (error) {
                console.error("注册失败原因:", error.message);
                alert("注册失败: " + error.message);
            }
        }
    };


    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isUser && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isUser && (
                <div>

                    {/* <nav className="navbar navbar-expand-lg fixed-top portfolio-navbar gradient navbar-dark">
                        <div className="container">
                            <a className="navbar-brand logo" href="#">先锋积分</a>
                            <button className="navbar-toggler" data-bs-target="#navbarNav" data-bs-toggle="collapse">
                                <span className="visually-hidden">Toggle navigation</span>
                                <span className="navbar-toggler-icon" />
                            </button>
                            <div className="collapse navbar-collapse" id="navbarNav">
                                <ul className="navbar-nav ms-auto">
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}`}>用户首页</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_GetOwnInfo`}>用户查询个人信息</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_updateOwnerInfo`}>修改个人信息</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_JoinActivity`}>参加活动</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_uploadMaterial`}>上传材料</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_ReacherPoint`}>查询积分</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_MaterialList`}>用户上传材料列表</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/Student_Info`}>查询用户学生信息</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/user/${address}/User_registerStudent`}>学生注册</Link>
                                    </li>
                                    <li className="nav-item">
                                        <Link className="nav-link" to={`/`}>退出登录</Link>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav> */}
                    <UserNavBar address={address} />
                    <main className="page hire-me-page">

                        <section className="portfolio-block hire-me">
                            <div className="foreground-component">
                                <Eye />
                                <div className="container">
                                    <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                        data-bs-theme="light"
                                        style={{
                                            backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                        }}
                                    >

                                        <div class="mb-3">
                                            <h1>学生注册</h1>
                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">真实姓名：</label>
                                                <input className="form-control item" id="name" type="text" placeholder="真实姓名" value={realName} onChange={(e) => setrealName(e.target.value)} />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">身份证号码：</label>
                                                <input className="form-control item" id="name" type="text" placeholder="身份证号码" value={idNumber} onChange={(e) => setidNumber(e.target.value)} />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">学号：</label>
                                                <input className="form-control item" id="name" type="text" placeholder="学号" value={studentIDNumber} onChange={(e) => setstudentIDNumber(e.target.value)} />
                                            </div>



                                            <div className="mb-3 mt-4">
                                                <button className="btn btn-primary btn-lg d-block w-100" onClick={RegisterStudent}>注册</button>
                                            </div>



                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>
                    </main>
                </div>
            )}
        </div>
    );
}

export default User_registerStudent;